﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "StructureStripFoundation.h"
#include "DbObjectUtils.h"
#include "GbmpBuiltInParameterDefinitionsNew.h"
#include "GcmpBuiltInParameterDefinitions.h"
#include "GmIStructureFactory.h"
#include "GmStructureDefaultElementParametersCustomizer.h"
#include "ICalculator.h"
#include "ICalculatorCollection.h"
#include "ICopyStrategyReporter.h"
#include "IDocument.h"
#include "IElement.h"
#include "IElementBasicInformation.h"
#include "IElementParameters.h"
#include "IElementParentReporter.h"
#include "IElementPosition.h"
#include "IElementStatus.h"
#include "IExternalDataComponent.h"
#include "IFamily.h"
#include "IInstance.h"
#include "IInstanceType.h"
#include "ILevel.h"
#include "IParameter.h"
#include "IParameterDefinitionLibrary.h"
#include "IPositionCurve2d.h"
#include "IPositionSingleAssociatedPlane.h"
#include "IRegenerator.h"
#include "IRegeneratorDataIdCreator.h"
#include "LevelUtils.h"
#include "StructureInstanceLevelUtils.h"
#include "StructureInstanceUtils.h"
#include "StructureStripFoundationInput.h"

#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gcmp;

namespace gcmp
{
    class StructureStripFoundationElementParametersCustomizer : 
        public GmStructureDefaultElementParametersCustomizer
    {
        DBOBJECT_DATA_BEGIN(gcmp, StructureStripFoundationElementParametersCustomizer, 
            gcmp::GmStructureDefaultElementParametersCustomizer, 
            4FD8829A-2F7D-4593-984F-0E2B1CDD06B6, gmstructure)
        DBOBJECT_DATA_END
    public:
        StructureStripFoundationElementParametersCustomizer(IElement* pElement);

        virtual bool IsPresetParameter(const UniIdentity& paramDefUid) const override;
    };
}

DBOBJECT_DATA_DEFINE(StructureStripFoundationElementParametersCustomizer)
{
    SetOwnerElement(nullptr);
}

StructureStripFoundationElementParametersCustomizer::StructureStripFoundationElementParametersCustomizer(
    IElement* pElement) : GmStructureDefaultElementParametersCustomizer(pElement)
{
}

bool StructureStripFoundationElementParametersCustomizer::IsPresetParameter(const UniIdentity& paramDefUid) const
{
    if (paramDefUid.HasSameValue(PARAMETER_UID(TopAssociatedLevelBuiltInParameter)) ||
        paramDefUid.HasSameValue(PARAMETER_UID(BuildingStoreyBuiltInParameter)) ||
        paramDefUid.HasSameValue(PARAMETER_UID(TopOffsetBuiltInParameter)) ||
        paramDefUid.HasSameValue(PARAMETER_UID(StripFoundationZPositioningTypeBuiltInParameter)) ||
        paramDefUid.HasSameValue(PARAMETER_UID(ConcreteStrengthGradeBuiltInParameter)))
    {
        return true;
    }

    return false;
}

IMPLEMENT_REGEN_FUNCTIONS(gcmp, StructureStripFoundation, Volume)
IMPLEMENT_REGEN_FUNCTIONS(gcmp, StructureStripFoundation, Length)
IMPLEMENT_REGEN_FUNCTIONS(gcmp, StructureStripFoundation, TopElevation)
IMPLEMENT_REGEN_FUNCTIONS(gcmp, StructureStripFoundation, BottomElevation)

DEFINE_STRUCTURE_INSTANCE_METHODS(StructureStripFoundation);

DBOBJECT_DATA_DEFINE(StructureStripFoundation)
{
    m_pOwnerElement = nullptr;
    SetVolume__(0);
    SetLength__(0);
    SetTopElevation__(0);
    SetBottomElevation__(0);
    SetConcreteStrengthGrade__(ConcreteStrengthGradeType::CSG_C30);
}

StructureStripFoundation* StructureStripFoundation::Create(const StructureStripFoundationInput* pInput)
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInput, L"pInput为空",L"GDMPLab",L"2024-03-30");

    IDocument* pDoc = pInput->Document;
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pDoc, L"pDoc为空",L"GDMPLab",L"2024-03-30");

    IInstanceType* pInstanceType = quick_cast<IInstanceType>(pDoc->GetElement(pInput->InstanceTypeId));
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInstanceType, L"pInstanceType为空",L"GDMPLab",L"2024-03-30");

    IInstance* pInstance = pInstanceType->CreateInstance(L"梁实例", pInput->CanBeShared, pInput->CreationOption, pInput->IsCreateGeometryRelationshipComponent);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInstance, L"pInstance为空",L"GDMPLab",L"2024-03-30");

    //设置instance的Unidentity
    if (pInput->categoryUid.IsValid())
    {
        pInstance->GetBasicInformation()->SetCategoryUid(pInput->categoryUid);
    }

    OwnerPtr<StructureStripFoundation> opStripFoundation = NEW_AS_OWNER_PTR(StructureStripFoundation);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(opStripFoundation, L"opStripFoundation为空",L"GDMPLab",L"2024-03-30");
    opStripFoundation->SetConcreteStrengthGrade__(pInput->ConcreteType);

    StructureStripFoundation* pFoundation = opStripFoundation.get();
    pFoundation->SetOwnerElement(pInstance);
    if (IExternalDataComponent * pExternalDataComponent = pInstance->GetExternalDataComponent())
    {
        pExternalDataComponent->RegisterExternalData(StructureStripFoundation::GetStaticClassSchema()->GetName(), TransferOwnership(opStripFoundation));
    }

    ElementId associatedPlaneId = pInput->AssociatedPlaneId;
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(associatedPlaneId.IsValid(), L"associatedPlaneId无效",L"GDMPLab",L"2024-03-30");

    const ILevel* pStoreyLevel = nullptr;
    if (pInput->StoreyId.IsValid())
    {
        pStoreyLevel = LevelUtils::GetLevelById(pDoc, pInput->StoreyId);
    }
    else
    {
        pStoreyLevel = StructureInstanceLevelUtils::GetStripFoundationStoreyLevelFromPositioningLevel(pDoc, associatedPlaneId);
    }
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pStoreyLevel, L"pStoreyLevel为空",L"GDMPLab",L"2024-03-30");

    bool bOk = StructureInstanceLevelUtils::CreateInstanceStoreyLevel(pInstance, pStoreyLevel);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(bOk, L"SetFoundationStoreyLevel失败",L"GDMPLab",L"2024-03-30");

    bOk = IElementPosition::CreateCurve2dOnTopAssociatedPlanePositionBehavior(pInstance, associatedPlaneId, pInput->PositionPoints);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(bOk, L"PositionBehavior创建失败",L"GDMPLab",L"2024-03-30");

    IElementPosition* pPositionBehavior = pInstance->GetElementPosition();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pPositionBehavior, L"pPositionBehavior为空",L"GDMPLab",L"2024-03-30");

    IPositionSingleAssociatedPlane* pPositionAssociatedPlane =
        quick_cast<IPositionSingleAssociatedPlane>(pPositionBehavior->GetPositionAssociatedPlane());
    DBG_WARN_AND_RETURN_FALSE_UNLESS(pPositionAssociatedPlane, L"pPositionAssociatedPlane为空",L"GDMPLab",L"2024-03-30");
    pPositionAssociatedPlane->SetOffset(pInput->AssociatedPlaneOffset);

    const IPositionCurve2d* pPosCurve2d = dynamic_cast<const IPositionCurve2d*>(pPositionBehavior->GetPositionGeometry());
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pPosCurve2d, L"pPosCurve2d为空",L"GDMPLab",L"2024-03-30");
    bOk = pInstance->SetCoordinateSystemsByCurve(pPosCurve2d->GetBaseCurve());
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(bOk, L"SetCoordinateSystemsByCurve失败",L"GDMPLab",L"2024-03-30");

    OwnerPtr<IParameter> paramZPositioningType = pInstance->GetElementParameters()->GetParameterByUid(PARAMETER_UID(StripFoundationZPositioningTypeBuiltInParameter));
    if (IParameter::IsValidParameter(paramZPositioningType))
    {
        paramZPositioningType->SetValueAsInt((int)pInput->ZPositioningType);
        pInstance->GetElementParameters()->SetParameter(paramZPositioningType.get());
    }

    if (pInstance->GetElementParameters())
    {
        OwnerPtr<IElementParametersCustomizer> opNewCustomizer = 
            NEW_AS_OWNER_PTR(StructureStripFoundationElementParametersCustomizer, pInstance);
        GmStructureDefaultElementParametersCustomizer::SetElementParametersCustomizer(
            pInstance, TransferOwnership(opNewCustomizer));
    }

    IElementStatus* pStatus = pInstance->GetStatus();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pStatus, L"无法获取状态集",L"GDMPLab",L"2024-03-30");
    pStatus->SetIsVisible(pInput->Visible);

    bOk = pDoc->GetRegenerator()->RegenerateElement(pInstance->GetElementId());
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(bOk, L"RegenerateElement失败",L"GDMPLab",L"2024-03-30");

    return pFoundation;
}

void StructureStripFoundation::UpdateForWeakParentDeletion(const std::set<ElementId>& deletedElementIds)
{
    return;
}

void StructureStripFoundation::ReportParents(IElementParentReporter& reporter) const
{
}

DECLARE_CALCULATOR_CREATOR(InstanceVolumeCalculator)
DECLARE_CALCULATOR_CREATOR(StructureInstanceLengthCalculator)
DECLARE_CALCULATOR_CREATOR(StructureStripFoundationTopElevationCalculator)
DECLARE_CALCULATOR_CREATOR(StructureStripFoundationBottomElevationCalculator)
void StructureStripFoundation::GetCalculators(ICalculatorCollection * calculators) const
{
    ADD_CALCULATOR(InstanceVolumeCalculator, GetDocument(), GetVolumeRdId());
    ADD_CALCULATOR(StructureInstanceLengthCalculator, GetDocument(), GetLengthRdId());
    ADD_CALCULATOR(StructureStripFoundationTopElevationCalculator, GetDocument(), GetTopElevationRdId());
    ADD_CALCULATOR(StructureStripFoundationBottomElevationCalculator, GetDocument(), GetBottomElevationRdId());

}

void StructureStripFoundation::ReportParameterDefinitions(std::vector<int>* pParamDefIds) const
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(pParamDefIds != nullptr, L"pParamDefUids为空",L"GDMPLab",L"2024-03-30");
    pParamDefIds->push_back(PARAMETER_ID(VolumeBuiltInParameter));
    pParamDefIds->push_back(PARAMETER_ID(LineFamilyLengthBuiltInParameter));
    pParamDefIds->push_back(PARAMETER_ID(TopElevationBuiltInParameter));
    pParamDefIds->push_back(PARAMETER_ID(BottomElevationBuiltInParameter));
    pParamDefIds->push_back(PARAMETER_ID(ConcreteStrengthGradeBuiltInParameter));
}

OwnerPtr<IParameter> StructureStripFoundation::GetNativeParameter(int paramDefId) const
{
    OwnerPtr<IParameter> param;
    ParameterAttributes pa = {false, false, true};
    if (paramDefId == PARAMETER_ID(VolumeBuiltInParameter))
    {
        //param = NEW_AS_OWNER_PTR(Parameter, GetDocument(), ParameterStorageType::Double, false, false,
            //true, PARAMETER_UID(VolumeBuiltInParameter), ParameterProcessType::GeneralOutput);
        param = IParameter::CreateParameter(GetDocument(), ParameterStorageType::Double, pa,
            PARAMETER_UID(VolumeBuiltInParameter), ParameterProcessType::GeneralOutput);
        param->SetValueAsDouble(GetVolume__());
        return TransferOwnership(param);
    }
    else if (paramDefId == PARAMETER_ID(LineFamilyLengthBuiltInParameter))
    {
        //param = NEW_AS_OWNER_PTR(Parameter, GetDocument(), ParameterStorageType::Double, false, false,
            //true, PARAMETER_UID(LineFamilyLengthBuiltInParameter), ParameterProcessType::GeneralOutput);
        param = IParameter::CreateParameter(GetDocument(), ParameterStorageType::Double, pa,
            PARAMETER_UID(LineFamilyLengthBuiltInParameter), ParameterProcessType::GeneralOutput);
        param->SetValueAsDouble(GetLength__());
        return TransferOwnership(param);
    }
    else if (paramDefId == PARAMETER_ID(ConcreteStrengthGradeBuiltInParameter))
    {
        //param = NEW_AS_OWNER_PTR(Parameter, GetDocument(), ParameterStorageType::Int, false, false,
            //true, PARAMETER_UID(ConcreteStrengthGradeBuiltInParameter), ParameterProcessType::GeneralInput);
        param = IParameter::CreateParameter(GetDocument(), ParameterStorageType::Int, pa,
            PARAMETER_UID(ConcreteStrengthGradeBuiltInParameter), ParameterProcessType::GeneralInput);
        param->SetValueAsInt((int)GetConcreteStrengthGrade__());
        return TransferOwnership(param);
    }
    else if (paramDefId == PARAMETER_ID(TopElevationBuiltInParameter))
    {
        //param = NEW_AS_OWNER_PTR(Parameter, GetDocument(), ParameterStorageType::Double, false, false,
            //true, PARAMETER_UID(TopElevationBuiltInParameter), ParameterProcessType::GeneralOutput);
        param = IParameter::CreateParameter(GetDocument(), ParameterStorageType::Double, pa,
            PARAMETER_UID(TopElevationBuiltInParameter), ParameterProcessType::GeneralOutput);
        param->SetValueAsDouble(GetTopElevation());
        return TransferOwnership(param);
    }
    else if (paramDefId == PARAMETER_ID(BottomElevationBuiltInParameter))
    {
        //param = NEW_AS_OWNER_PTR(Parameter, GetDocument(), ParameterStorageType::Double, false, false,
            //true, PARAMETER_UID(BottomElevationBuiltInParameter), ParameterProcessType::GeneralOutput);
        param = IParameter::CreateParameter(GetDocument(), ParameterStorageType::Double, pa,
            PARAMETER_UID(BottomElevationBuiltInParameter), ParameterProcessType::GeneralOutput);
        param->SetValueAsDouble(GetBottomElevation());
        return TransferOwnership(param);
    }

    return nullptr;
}

bool StructureStripFoundation::SetNativeParameter(const IParameter *param, std::wstring* errorMsg/* = nullptr*/)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(param, L"param is null.",L"GDMPLab",L"2024-03-30");

    if (param->GetParameterDefinitionId() == PARAMETER_ID(VolumeBuiltInParameter))
    {
        SetVolume(param->GetValueAsDouble());
        return true;
    }
    else if (param->GetParameterDefinitionId() == PARAMETER_ID(TopElevationBuiltInParameter))
    {
        SetTopElevation(param->GetValueAsDouble());
        return true;
    }
    else if (param->GetParameterDefinitionId() == PARAMETER_ID(BottomElevationBuiltInParameter))
    {
        SetBottomElevation(param->GetValueAsDouble());
        return true;
    }
    else if (param->GetParameterDefinitionId() == PARAMETER_ID(LineFamilyLengthBuiltInParameter))
    {
        SetLength(param->GetValueAsDouble());
        return true;
    }
    else if (param->GetParameterDefinitionId() == PARAMETER_ID(ConcreteStrengthGradeBuiltInParameter))
    {
        SetConcreteStrengthGrade((ConcreteStrengthGradeType)param->GetValueAsInt());
        return true;
    }
    return false;
}

bool StructureStripFoundation::IsParameterModifiable(int paramDefId) const
{
    if (paramDefId == PARAMETER_ID(TopElevationBuiltInParameter) ||
        paramDefId == PARAMETER_ID(BottomElevationBuiltInParameter))
    {
        return false;
    }
    return true;
}

void StructureStripFoundation::Report(const ICopyContext & copyContext, ICopyStrategyReporter& reporter) const
{
    reporter.ReportToCopy(GetOwnerElementId());
}

IDocument* StructureStripFoundation::GetDocument() const
{
    return m_pOwnerElement ? m_pOwnerElement->GetDocument() : nullptr;
}

ElementId StructureStripFoundation::GetOwnerElementId() const
{
    return m_pOwnerElement ? m_pOwnerElement->GetElementId() : ElementId::InvalidID;
}

NdbObject* StructureStripFoundation::GetTopOwnerObject() const
{
    if (!GetDocument())
        return nullptr;

    return quick_cast<NdbObject>(GetDocument()->GetElement(GetOwnerElementId()));
}

